package com.sleep.god.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 时间操作工具
 */
public class DateUtils {
    /**
     * 获取时间段内每一天
     *
     * @param start
     * @param end
     * @return
     */
    public static List<String> handleCirculationDate(String start, String end) {
        List<String> listDate = new ArrayList<String>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date startDate = dateFormat.parse(start);
            Date endDate = dateFormat.parse(end);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            int i = 0;
            while (calendar.getTime().before(endDate)) {
                System.out.println(dateFormat.format(calendar.getTime()));
                listDate.add(dateFormat.format(calendar.getTime()));
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                i++;
            }
            System.out.println(i);
            return listDate;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * string to date yyyy-MM-dd HH:mm:ss
     *
     * @param source
     * @return
     * @throws ParseException
     */
    public static Date stringToDateYMDHMS(String source) throws ParseException {
        return stringToDate(source, "yyyy-MM-dd HH:mm:ss");
    }


    /**
     * string to date
     *
     * @param source 时间
     * @param format 格式
     * @return
     * @throws ParseException
     */
    public static Date stringToDate(String source, String format) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.parse(source);
    }

    /**
     * date to string
     *
     * @param date   时间
     * @param format 格式
     * @return
     */
    public static String dateToString(Date date, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }

    /**
     * 返回当前时间指定格式的数据
     *
     * @param format
     * @return
     */
    public static String getNowDateToString(String format) {
        return dateToString(new Date(), format);
    }

    /**
     * 计算两个日期相差几天
     *
     * @param d1
     * @param d2
     * @return
     */
    public static final int getDayFromTimeDiff(Date d1, Date d2) {
        if (d1 == null || d2 == null) {
            return 0;
        }
        long l1 = d1.getTime();
        long l2 = d2.getTime();
        long diff = l2 - l1;
        int day = (int) (diff / (1000 * 3600 * 24));
        return day;

    }
}
